'use client';

import { useEffect, useState } from 'react';
import { use } from 'react';
import { useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import '@uiw/react-markdown-preview/markdown.css';

// 动态导入Markdown预览组件以避免SSR问题
const MarkdownPreview = dynamic(
  () => import('@uiw/react-markdown-preview').then((mod) => mod.default),
  { ssr: false }
);

interface Document {
  id: string;
  title: string;
  content: string;
  published: boolean;
  createdAt: string;
  updatedAt: string;
}

export default function DocumentPage({ params }: { params: { id: string } }) {
  const resolvedParams = use(params);
  const router = useRouter();
  const [document, setDocument] = useState<Document | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    fetchDocument();
  }, []);

  const fetchDocument = async () => {
    try {
      const response = await fetch(`/api/documents/${resolvedParams.id}`);
      if (!response.ok) {
        throw new Error('获取文档失败');
      }
      const data = await response.json();
      setDocument(data);
    } catch (err) {
      setError('获取文档失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!confirm('确定要删除这篇文档吗？')) return;

    try {
      const response = await fetch(`/api/documents/${resolvedParams.id}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        throw new Error('删除文档失败');
      }

      router.push('/documents');
    } catch (err) {
      alert('删除文档失败');
    }
  };

  if (loading) return <div className="p-4">加载中...</div>;
  if (error) return <div className="p-4 text-red-500">{error}</div>;
  if (!document) return <div className="p-4">文档不存在</div>;

  return (
    <div className="p-4 max-w-4xl mx-auto">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">{document.title}</h1>
        <div className="flex gap-4">
          <button
            onClick={() => router.push(`/documents/${resolvedParams.id}/edit`)}
            className="text-blue-500 hover:text-blue-600"
          >
            编辑
          </button>
          <button
            onClick={handleDelete}
            className="text-red-500 hover:text-red-600"
          >
            删除
          </button>
        </div>
      </div>

      <div className="mb-4 text-sm text-gray-500">
        最后更新: {new Date(document.updatedAt).toLocaleString()}
      </div>

      <div data-color-mode="light" className="prose max-w-none">
        <MarkdownPreview source={document.content} />
      </div>
    </div>
  );
}